package com.open.capacity.reptile.controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.finance.entity.Pz;
import com.open.capacity.finance.service.PzService;
import com.open.capacity.finance.util.PdfPz;
import com.open.capacity.finance.util.PdfWatermark;
import com.open.capacity.user.service.SysConfigService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.file.FileUtils;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.list.TreeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 凭证
 *
 * @author
 * @email
 * @date 2020-06-05 17:40:41
 */
@Slf4j
@RestController
@RequestMapping("glvous")
@Api(tags = "凭证")
public class GdszczGlVouController {

    @Autowired
    private PzService pzService;

    @Autowired
    private SysConfigService sysConfig;

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = pzService.pageAll(params);
        return pageResult;
    }


    /**
     * 凭证树
     */
    @RequestMapping("/tree")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result<List<TreeVo>> tree(@RequestParam Map<String, Object> params) {
        List<Pz> pzs = pzService.findAllSimple(params);
        TreeMap<String, List<Pz>> treeMap = pzs.stream().filter(item -> StringUtil.isNotEmpty(item.getPzlxCode())).collect(Collectors.groupingBy(Pz::getPzlx, TreeMap::new, Collectors.toList()));

        List<TreeVo> treeList = new TreeList();
        for (Map.Entry entry : treeMap.entrySet()) {
            String key = entry.getKey().toString();
            List<Pz> list = (List) entry.getValue();
            TreeVo node = new TreeVo();
            node.setId(key);
            node.setText(key);
            node.setTitle(key);
            node.setValue(key);
            node.setShowcheck(false);
            node.setIsexpand(true);
            node.setComplete(false);
            node.setParentId("0");
            treeList.add(node);
            for (Pz value : list) {
                TreeVo node1 = new TreeVo();
                node1.setId(value.getPzid());
                String tag = "";
                if (value.getIsTemp() != null && value.getIsTemp().equals(1)) {
                    tag = "(临)";
                }
                node1.setText(value.getPzh() + tag + " - " + value.getZy());
                node1.setTitle(value.getZy());
                node1.setValue(value.getPzid());
                node1.setShowcheck(false);
                node1.setIsexpand(false);
                node1.setComplete(true);
                node1.setParentId(key);
                treeList.add(node1);
            }
        }

        return Result.succeed(TreeVo.RecursiveBuilder(treeList, "0"));
    }

    /**
     * 凭证树(查找对冲)
     */
    @RequestMapping("/tree_hedge")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result<List<TreeVo>> tree_hedge(@RequestParam Map<String, Object> params) {
        List<Pz> pzs = pzService.findAllSimple_hedge(params);
        TreeMap<String, List<Pz>> treeMap = pzs.stream().filter(item -> StringUtil.isNotEmpty(item.getPzlxCode())).collect(Collectors.groupingBy(Pz::getPzlx, TreeMap::new, Collectors.toList()));

        List<TreeVo> treeList = new TreeList();
        for (Map.Entry entry : treeMap.entrySet()) {
            String key = entry.getKey().toString();
            List<Pz> list = (List) entry.getValue();
            TreeVo node = new TreeVo();
            node.setId(key);
            node.setText(key);
            node.setTitle(key);
            node.setValue(key);
            node.setShowcheck(false);
            node.setIsexpand(true);
            node.setComplete(false);
            node.setParentId("0");
            treeList.add(node);
            for (Pz value : list) {
                TreeVo node1 = new TreeVo();
                node1.setId(value.getPzid());
                String tag = "";
                if (value.getIsTemp() != null && value.getIsTemp().equals(1)) {
                    tag = "(临)";
                }
                node1.setText(value.getPzh() + tag + " - " + value.getZy());
                node1.setTitle(value.getZy());
                node1.setValue(value.getPzid());
                node1.setShowcheck(false);
                node1.setIsexpand(false);
                node1.setComplete(true);
                node1.setParentId(key);
                treeList.add(node1);
            }
        }

        return Result.succeed(TreeVo.RecursiveBuilder(treeList, "0"));
    }


    /**
     * 查询单条记录
     */
    @RequestMapping("/findById")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result findById(String id) {
        return Result.succeed(pzService.findById(id));
    }

    /**
     * 查询单条记录
     */
    @RequestMapping("/findByIds")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result findByIds(String ids) {
        return Result.succeed(pzService.findByIds(ids));
    }


    /**
     * 查询前单
     */
    @RequestMapping("/pre")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result findPre(@DateTimeFormat(pattern = "yyyy-MM-dd") Date pzrq, String pzlxCode, String keyValue) {
        return Result.succeed(pzService.findPre(keyValue, pzrq, pzlxCode));
    }

    /**
     * 查询后单
     */
    @RequestMapping("/next")
    @PreAuthorize("hasAnyAuthority('pz:pz:list')")
    public Result findNext(@DateTimeFormat(pattern = "yyyy-MM-dd") Date pzrq, String pzlxCode, String keyValue) {
        return Result.succeed(pzService.findNext(keyValue, pzrq, pzlxCode));
    }


    /**
     * 导出pdf
     *
     * @return
     */
    @GetMapping("/export/pdf")
    public void exportPdf(String ids, HttpServletRequest request, HttpServletResponse response) {
        List<Pz> pzList = pzService.findByIds(ids);
        String[] headNames = {"序号", "摘要", "会计科目", "借", "贷"};
        float colWidths[] = {40, 200, 260, 80, 80};

        String filePath = fileuploadPath + "/temp/pdf/pz.pdf";
        Document document = new Document(PageSize.A4);// 建立一个Document对象
        try {
            File file = new File(filePath);
            if (file.exists())
                file.delete();
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setPageEvent(new PdfWatermark("禁止外泄"));// 水印
//            writer.setPageEvent(new PdfHeaderFooter());// 页眉/页脚
            document.open();
            new PdfPz().generatePDF(document, pzList, headNames, colWidths);
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            document.close();
        }
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, "pz.pdf"));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (false) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 导出pdf
     *
     * @return
     */
    @GetMapping("/export/pdfAll")
    public void exportPdfAll(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        params.put("isQc", "0");
        params.put("orderby", "kjqj,pzh");
        List<Pz> pzList = pzService.findExports(params);
        String[] headNames = {"序号", "摘要", "会计科目", "借", "贷"};
        float colWidths[] = {40, 200, 260, 80, 80};

        String filePath = fileuploadPath + "/temp/pdf/pz.pdf";
        Document document = new Document(PageSize.A4);// 建立一个Document对象
        try {
            File file = new File(filePath);
            if (file.exists())
                file.delete();
            file.createNewFile();
            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
            writer.setPageEvent(new PdfWatermark("禁止外泄"));// 水印
//            writer.setPageEvent(new PdfHeaderFooter());// 页眉/页脚
            document.open();
            new PdfPz().generatePDF(document, pzList, headNames, colWidths);
        } catch (Exception e) {
            log.error(e.toString());
        } finally {
            document.close();
        }
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, "pz.pdf"));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (false) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}
